/**
 * 核心技术支持
 * IT渠道网 小程序商城
 * 13873174181 微信同号
 */
import {Product} from 'product-model';
import {Cart} from '../cart/cart-model.js';
var product = new Product();
var cart = new Cart();
var WxParse = require('../../wxParse/wxParse.js'); // 引入html转换wxml插件

Page({
  data:{
    minusStatuses: ['disabled', 'normal'],
    index: 0,
    winWidth: 0,
    winHeight: 0,
    wpheight: 0, //wxparse高度
    currentTab: 0, //tab切换
    productId: 0,
    itemData: {},
    buynum: 1,
    cartNum: 0,
    favorited: false, //收藏标识
    restUrl: product.getUrl(),
    // 产品图片轮播
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    showModalStatus: false,
    // 规格
    specificationList: [], //sku集合
    sku: {}, //sku当前单例
    specificationItems: {}, //存储用户选择的规格 默认初始值
    customAttributeItems: [], //产品参数
    itemImgList: [], //所有图
    currentImg: '', //已选sku图
    skuList: [] //sku详情集合
  },
  /**
   * 弹窗效果
   */
  setModalStatus: function(e) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export()
    });
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatus: true
      })
    };
    setTimeout(function () {
      animation.translateY(0).step();
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 200);
    if (e.currentTarget.dataset.type == 1) {
      this.setData({
        buynow: true
      })
    };
  },
  /**
   * 数量+-
   */
  changeNum: function(e) {
    var that = this;
    if (e.target.dataset.alphaBeta == 0) {
      if (this.data.buynum <= 2) {
        this.setData({
          buynum: 1,
          index: 0
        })
      }else{
        this.setData({
          buynum: this.data.buynum - 1,
          index: 1
        })
      };
    }else{
      this.setData({
        buynum: this.data.buynum + 1,
        index: 1
      })
    };
  },
  /**
   * 获取数据
   */
  onLoad: function(option) {
    this.initNavHeight(); // 初始窗口
    var that = this;
    that.setData({
      productId: option.id
    });
    that.loadProductDetail();
    // 购物车数 收藏 足迹
    that.loadShowData();
    // 相关推荐
    that.loadHotList();
  },
  /**
   * 判断规格选中
   * 用户选择规格
   */
  selectSpecification: function(event) {
    var key = event.currentTarget.dataset['key'], value = event.currentTarget.dataset['value'];
    var obj = this.data.specificationItems;
    obj[key] = value;
    this.setData({
      specificationItems: obj
    })
    this.searchSku(); // 查询重新给sku赋值
    this.currentImg();
  },
  /** 
   * 匹配两个对象是否相等 map2为已选
   */
  matchObject: function(map1, map2) {
    map1 = JSON.parse(map1);
    for(var k in map1){
      if(map1[k] != map2[k]){ // {'网络':'移动3G','机身内存':16G}
        return false;         // {'网络':'移动3G','机身内存':16G,'颜色':'土豪金'} 相互对比
      }
    }
    for(var k in map2){
      if(map2[k] != map1[k]){
        return false;
      }
    }
    return true;
  },
  /**
   * 根据规格查询sku
   */
  searchSku: function() {
    var skuList = this.data.skuList;
    for (var i in skuList) { // 两个规格对象匹配,有相同显示sku价格
       if (this.matchObject(skuList[i].spec, this.data.specificationItems)) {
          skuList[i].price = skuList[i].price.toFixed(2);
          this.setData({
            sku: skuList[i] // 重新赋值sku
          })
          return;
       }
    }
    this.setData({
      sku: {id:0, title:'', price:0, num:0} // 未匹配到数据时
    })
  },
  /**
   * 已选规格图
   */
  currentImg: function() {
    var color='', url='';
    // 获取颜色值
    for(var k in this.data.specificationItems){
      if (k.indexOf('颜色')>-1) color = this.data.specificationItems[k]
    }
    // 获取图
    for(var e in this.data.itemImgList){
      if (this.data.itemImgList[e].color.indexOf(color)>-1) url = this.data.itemImgList[e].url
    }
    this.setData({
      currentImg: url
    })
  },
  /**
   * 商品详情数据获取
   */
  loadProductDetail: function() {
    var that = this, id = that.data.productId;
    product.getDetailInfo(id, (res) => {
      // 封装
      var list = res.itemList, fList = [];
      for(var k in list) {
        var obj = {};
        obj.id = list[k].id;
        obj.title = list[k].title;
        obj.goodsId = list[k].goodsId;
        obj.seller = list[k].seller;
        obj.sellerId = list[k].sellerId;
        obj.marketPrice = list[k].marketPrice;
        obj.price = list[k].price;
        obj.spec = list[k].spec;
        obj.num = list[k].num;
        fList.push(obj);
      }
      // price
      list[0].price = list[0].price.toFixed(2);
      that.setData({
        itemData: res,
        sku: list[0], // 默认
        specificationItems: JSON.parse(list[0].spec), // 已择规格 默认
        specificationList: JSON.parse(res.goodsDesc.specificationItems), // sku集合
        customAttributeItems: JSON.parse(res.goodsDesc.customAttributeItems), // 产品参数
        itemImgList: JSON.parse(res.goodsDesc.itemImages), // 所有图
        skuList: fList, // sku详情集合
      })
      WxParse.wxParse('content', 'html', res.goodsDesc.introduction, that, 3);
      that.currentImg();
      console.log(0, res);
    });
  },
  /**
   * 添加到购物车
   */
  addShopCart: function() {
      // 防止快速重复点击
      if (this.data.isFly) {
          return
      }
      this.addToCart();
  },
  /**
   * 将当前商品数据添加到购物车缓存中
   */
  addToCart: function() {
    var that = this;
    this.setData({
        isFly: true
    });
    var sku = this.data.sku;
    sku['image'] = this.data.currentImg;
    // 加入购物车:商品,数量
    cart.add(sku, this.data.buynum);
    // 立即
    if (that.data.buynow) {
      wx.switchTab({
        url: '/pages/cart/cart'
      });
    };
    // 加购
    wx.showToast({
        title: '加入购物车成功',
        icon: 'success',
        duration: 1000
    });
    setTimeout(function(){ 
      that.setData({
        showModalStatus: false,
        isFly: false,
        cartNum: cart.getCartTotalCounts().counts2
      })
    }, 500);
  },
  /**
   * 购物车数 收藏 足迹
   */
  loadShowData: function() {
    var that = this,
        id = that.data.productId;
    this.setData({
      cartNum: cart.getCartTotalCounts().counts2
    });
    // collection
    product.getCollect(id, (res) => {
      if (res.status==200) {
        that.setData({
          favorited: true
        });
      }
    });
    // view
    product.addView(id);
  },
  /**
   * 收藏商品
   */
  collectGoods: function() {
    var that = this,
        id = that.data.productId;
    if (this.data.favorited) {
      product.deleteCollection(id, (res) => {
        if (res.status=200) {
          that.setData({
            favorited: false // 取消
          });
        }
      });
    } else {
      product.addUserCollection(id, (res) => {
        if (res.status=200) {
          that.setData({
            favorited: true // 收藏
          });
        }
      });
    }
  },
  /**
   * 跳转到购物车
   */
  onCartTap: function() {
      wx.switchTab({
          url: '/pages/cart/cart'
      });
  },
  /**
   * 获取系统信息
   */
  initNavHeight: function() {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          wpheight: res.windowHeight - (res.windowHeight*0.05) - 80
        });
      }
    });
  },
  /**
   * tab切换
   */
  swichNav: function(e) {
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  /**
   * 相关推荐
   */
  loadHotList: function() {
    var that = this;
    product.getHotData(1, (data) => {
      // 截取字符
      data.forEach((item) => {
        item.goodsName = item.goodsName.substring(0, 32);
        item.price = item.price.toFixed(2);
      })
      that.setData({
        hotData: data,
      })
    })
  },
  /**
   * 商品详情
   */
  onProductsItemTap: function(event) {
    var id = product.getDataSet(event, 'id');
    wx.navigateTo({
      url: '../product/product?id=' + id
    })
  }
})